using System;
using System.Net;
using System.Net.Sockets;
using System.Windows.Forms;

namespace WIT.Global;

/// <summary>
/// TCPClient对象
/// </summary>
public class TCPClient
{
	private TcpClient _network;

	/// <summary>
	/// 数据接收缓存区
	/// </summary>
	public byte[] buffer = new byte[2048];

	private string _name { get; set; }

	/// <summary>
	/// 客户端名称
	/// </summary>
	public string Name => _name;

	private string _ip { get; set; }

	/// <summary>
	/// 客户端IP
	/// </summary>
	public string IP => _ip;

	private int _port { get; set; }

	/// <summary>
	/// 客户端Port
	/// </summary>
	public int Port => _port;

	/// <summary>
	/// TCP客户端
	/// </summary>
	public TcpClient NetWork
	{
		get
		{
			return _network;
		}
		set
		{
			_network = value;
			_network.NoDelay = true;
			SetProperties();
		}
	}

	/// <summary>
	/// 设置客户端属性
	/// </summary>
	public void SetProperties()
	{
		if (_network.Connected)
		{
			IPEndPoint iPEndPoint = (IPEndPoint)_network.Client.RemoteEndPoint;
			_ = (IPEndPoint)_network.Client.LocalEndPoint;
			_name = iPEndPoint.ToString();
			_ip = iPEndPoint.Address.ToString();
			_port = iPEndPoint.Port;
		}
	}

	/// <summary>
	/// 断开客户端连接
	/// </summary>
	public void DisConnect()
	{
		try
		{
			if (_network != null && _network.Connected)
			{
				_network.GetStream().Close();
				_network.Close();
			}
		}
		catch (Exception ex)
		{
			MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Hand);
		}
	}
}
